package com.platform.controller;

import java.beans.IntrospectionException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.platform.annotation.RequestBean;
import com.platform.base.PageUtil;
import com.platform.base.R;
import com.platform.base.mvc.BaseController;
import com.platform.dto.User;
import com.platform.dto.UserRole;
import com.platform.dto.UserSearchVo;
import com.platform.entity.ExcelColumns;
import com.platform.ext.offices.poi.excel.ExcelUtil;
import com.platform.ext.offices.poi.utils.DownLoadUtil;
import com.platform.logger.annotation.ApiLog;
import com.platform.service.IUser;
import com.platform.service.IUserRole;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 
 * <p> Title:Ygxx Mapper</p>
 * <p> Description:  记录部门员工的信息</p>
 * <p> Copyright: Copyright (c) 2019 </p>
 * <p> Company: </p>
 *
 * @author wys
 * @version 1.0
 */
@Controller
@RequestMapping("/user") 
@Api(tags="OMS-用户管理模块")
public class UserController extends BaseController{
	
	@Autowired
    private IUser services;
    
	@Autowired
    private IUserRole userRoleService;
    /**
     *  
     * selectAll(加载数据)
     * 
     * @param request
     * @param response
     * @param session
     * @return Object 可以是 JSON 或者 XML
     * @exception 
     * @version  1.0.0
     */
    @RequestMapping(value="data",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="分页查询")
    public Object selectAll(@RequestBean User dto,Integer start,Integer limit,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
        PageUtil pageUt = new PageUtil();
        pageUt.setPageIndex(start);
        pageUt.setPageSize(limit);
        pageUt.setParams(BeanUtil.beanToMap(dto));
        List<User> servicesList = services.selectByPaging(pageUt);
        return R.success(servicesList, pageUt.getTotal());
    }
    
    @RequestMapping(value="dataAll",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="查询所有数据")
    public Object select(User dto,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
        List<User> servicesList = services.selectAll(BeanUtil.beanToMap(dto));
        return R.success(servicesList);
    }
    
    @RequestMapping(value="selectUserByRole",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="根据角色查询用户数据")
    public Object selectUserByRole(String roleId,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
            Map<String,Object> searchRoleMap = MapUtil.newHashMap();
            searchRoleMap.put("rolecode", roleId);
            List<UserRole> userRoleList = userRoleService.selectAll(searchRoleMap);
            List<User> servicesList = new ArrayList<User>();
            for(UserRole userRole : userRoleList) {
                servicesList.add(services.get(userRole.getId()));
            }
            return R.success(servicesList);
    }
    
    
    /**
     *  
     * delete(删除数据)
     * 
     * @param request
     * @param response
     * @param session
     * @return Object 可以是 JSON 或者 XML
     * @exception 
     * @version  1.0.0
     */
    @ApiLog(value="删除用户信息",desc="系统用户数据删除")
    @SuppressWarnings("all")
    @RequestMapping(value="delete",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="删除数据")
    public Object delete(String ids, HttpServletRequest request, HttpServletResponse response,
            HttpSession session) throws IOException {
    	boolean isSuccess = false;
    	String[] idArray = ids.split(",");
    	for(int i=0;i<idArray.length;i++) {
    		User user = services.get(idArray[i]);
    		isSuccess = services.delete(user);
    	}
    	return R.success();
    }
    
    /**
     *  
     * insert(新增数据)
     * 
     * @param request
     * @param response
     * @param session
     * @return Object 可以是 JSON 或者 XML
     * @exception 
     * @version  1.0.0
     */
    @ApiLog(value="新增用户信息",desc="系统用户数据保存")
    @RequestMapping(value="save",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="新增数据")
    public Object insert(@Valid User dto,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
    	dto.setCreateDate(new Date(System.currentTimeMillis()));
    	dto.setCreater(getName());
    	if(services.insert(dto)) {
    		return R.success();
    	}else {
    		return R.fail();
    	}
    }
    
    @ApiLog(value="注册账号",desc="新账号注册")
    @RequestMapping(value="registerAccount",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="新账号注册")
    public R<?> registerAccount(@Valid User dto) {
    	dto.setCreateDate(new Date(System.currentTimeMillis()));
    	dto.setCreater("系统");
    	return services.insertByCreateAccount(dto);
    }
    
    /**
     *  
     * selectAll(修改数据)
     * 
     * @param request
     * @param response
     * @param session
     * @return Object 可以是 JSON 或者 XML
     * @exception 
     * @version  1.0.0
     */
    @ApiLog(value="修改用户信息",desc="系统用户数据修改")
    @RequestMapping(value="edit",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="修改数据")
    public Object update(@Valid User dto,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
    	dto.setLastModifyDate(new Date(System.currentTimeMillis()));
    	dto.setLastModifier(getName());
    	if(services.update(dto)){
    		return R.success();
    	}else {
    		return R.fail();
    	}
    }
    
    @ApiLog(value="重置用户登录密码",desc="系统用户数据密码重置")
    @RequestMapping(value="resetPassword",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="重置密码")
    public Object resetPassword(String id,String password,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
    	boolean isSuccess = false;
    	String[] ids = id.split(",");
    	for(String code : ids) {
    		User dto = new User();
    		dto.setId(Long.valueOf(Long.valueOf(code)));
    		dto.setPassword(password);
    		if(services.update(dto)){
    			isSuccess=true;
        	}
    	}
    	if(isSuccess){
    		return R.success();
    	}else {
    		return R.fail();
    	}
    }
    
    /**
     * @Title: changeState   
     * @Description: 修改用户状态
     * @param id
     * @param state	1 正常 2 离职 3限制登录
     * @param request
     * @param response
     * @param session
     * @return      
     * Object
     */
    @ApiLog(value="修改用户状态",desc="系统用户数据修改用户状态")
    @RequestMapping(value="changeState",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="修改用户状态")
    public Object changeState(String id,String state,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
    	boolean isSuccess = false;
    	String[] ids = id.split(",");
    	for(String code : ids) {
    		User dto = new User();
    		dto.setId(Long.valueOf(Long.valueOf(code)));
    		dto.setJobstate(Long.valueOf(state));
    		dto.setLastModifyDate(new Date(System.currentTimeMillis()));
        	dto.setLastModifier(getName());
    		if(services.update(dto)){
    			isSuccess = true;
        	}
    	}
    	if(isSuccess){
    		return R.success();
    	}else {
    		return R.fail();
    	}
    }
    
    /**
     *  
     * selectAll(获取单条数据)
     * 
     * @param request
     * @param response
     * @param session
     * @return Object 可以是 JSON 或者 XML
     * @exception 
     * @version  1.0.0
     */
    @RequestMapping(value="find",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="获取单条数据")
    public Object get(String code, HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
        return services.get(code);
    }
    
    @RequestMapping(value="selectUserListByRole",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation("根据角色编号查询对应用户")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "bean", value = "数据对象", required = true, dataType = "UserSearchVo"),
        @ApiImplicitParam(name = "start", value = "页码", required = true, dataType = "int"),
        @ApiImplicitParam(name = "limit", value = "每页显示条数", required = true, dataType = "int")
	})
    public R<?> selectUserListByRole(UserSearchVo userSearchVo,int start,int limit) {
    	return services.selectUserListByRole(userSearchVo, start, limit);
    }
    
    
    
    @ApiOperation(value="导出用户数据")
    @RequestMapping(value = "/exportToExcel",method=RequestMethod.GET)
    public void exportToExcel(@RequestParam Map<String,Object> params)  throws IOException{
    	//参数解析
    	List<ExcelColumns> columns = JSONUtil.parseArray(params.get("columns").toString()).toList(ExcelColumns.class);
    	boolean isPDF = params.get("toPdf") != null?Boolean.parseBoolean(params.get("toPdf").toString()):false;	//是否导出当前页
    	String protalParamsStr = params.get("protalParams").toString();
    	@SuppressWarnings("unchecked")
    	Map<String,Object> protalParams = JSONUtil.toBean(protalParamsStr, Map.class);
    	boolean colorless 	= Boolean.parseBoolean(params.get("colorless").toString());
    	boolean usemonetary = Boolean.parseBoolean(params.get("usemonetary").toString());
    	boolean sumless 	= Boolean.parseBoolean(params.get("sumless").toString());
    	boolean splitCell 	= Boolean.parseBoolean(params.get("splitCell").toString());
    	boolean watermark 	= Boolean.parseBoolean(params.get("watermark").toString());
    	String openPassword = params.get("openPassword").toString();
    	String userName		= params.get("userName").toString();
    	String deptname		= params.get("deptname").toString();
    	String systemName	= params.get("systemName").toString();
    	String modularName = params.get("modularText").toString();
    	//生成
    	PageUtil pg = new PageUtil();
    	pg.setPageIndex(Integer.valueOf(params.get("currentPage").toString()));
    	pg.setPageSize(Integer.valueOf(params.get("pageSize").toString()));
    	pg.setParams(protalParams);
    	List<User> exportData = services.selectByPaging(pg);
    	OutputStream osExcel = ExcelUtil.generateExcelOrPDF(modularName,exportData,protalParams,columns,colorless,usemonetary,sumless,splitCell,watermark,openPassword,userName,deptname,systemName);
    	if(isPDF) {
    		OutputStream osPDF = DownLoadUtil.excelStreamToPDFStream(new ByteArrayInputStream(((ByteArrayOutputStream) osExcel).toByteArray()));
    		String fn = modularName + "列表.pdf";
    		download(osPDF, fn, response);
    	}else {
    		String fn = modularName + "列表.xls";
    		download(osExcel, fn, response);
    	}
    }
	
}
